package com.peng.user.controller;

import com.google.gson.Gson;
import com.peng.base.exception.GuliException;
import com.peng.user.entity.UcenterMember;
import com.peng.user.service.UcenterMemberService;
import com.peng.user.utils.ConstantProperties;
import com.peng.user.utils.HttpClientUtils;
import com.peng.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApiController {
    @Autowired
    private UcenterMemberService ucenterMemberService;

    //生成微信扫描二维码,   %s 相当于?占位符
    @GetMapping("/login")
    public String getWxCode(){
        //使用code和appid以及appscrect换取access_token
        String baseUrl ="https://open.weixin.qq.com/connect/qrconnect"
                +"?appid=%s"
                +"&redirect_uri=%s"
                +"&response_type=code"
                +"&scope=snsapi_login"
                +"&state=%s"
                +"#wechat_redirect";
        String wxRedirectUrl = ConstantProperties.WX_REDIRECT_URL;
        try {
            wxRedirectUrl = URLEncoder.encode(wxRedirectUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = String.format(baseUrl, ConstantProperties.WX_APP_ID, wxRedirectUrl, "dp");
        return "redirect:"+url;
    }

    //扫码后的回调函数，获取登陆人的信息
    @GetMapping("/callback")
    public String callback(String code,String state, HttpSession session){
        try {
            //获取code值，临时票据，类似于验证码
            //拿着code，去请求微信固定的地址，得到两个值 access_token 和 openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token"+
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            String accessTokenUrl = String.format(baseAccessTokenUrl, ConstantProperties.WX_APP_ID, ConstantProperties.WX_APP_SECRET, code);
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            if (accessTokenInfo==null){
                throw new GuliException(20001,"登录异常");
            }
            //从accessTokenInfo中获取出  access_token 和 openid 的值
            //将 accessTokenInfo 转换成 map集合，根据map的key 就可以获取对应的value
            //使用json转换工具
            Gson gson = new Gson();
            HashMap<String, String> accessTokenMap = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = accessTokenMap.get("access_token");
            String openid = accessTokenMap.get("openid");
            UcenterMember member= ucenterMemberService.getUserByOpenId(openid);
            if (member==null){
                //拿着 access_token 和 openid 的值再去请求微信提供的固定地址
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String userInfo = HttpClientUtils.get(userInfoUrl);
                if (userInfo==null){
                    throw new GuliException(20001,"登录异常");
                }
                HashMap<String, String> userMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = userMap.get("nickname");
                String headimgurl = userMap.get("headimgurl");
                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                ucenterMemberService.save(member);
            }
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            return "redirect:http://localhost:3000?token="+jwtToken;
        }catch (Exception e){
            e.printStackTrace();
            throw new GuliException(200001,"登录失败");
        }

    }
}
